import SwiftUI

// 自动功能视图
struct AutoFunctionsView: View {
    @EnvironmentObject var tcpCarService: TCPCarService
    
    @State private var isAutoTracking = false
    @State private var isAutoAvoidance = false
    @State private var isAutoFollow = false
    
    @State private var avoidanceDistance = 0.5
    @State private var followSpeed = 0.6
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                // 标题
                Text("自动功能")
                    .font(.title)
                    .fontWeight(.bold)
                    .padding(.top)
                
                // 自动功能列表
                VStack(spacing: 15) {
                    // 自动轨迹跟踪
                    FunctionToggleRow(
                        title: "自动轨迹跟踪",
                        description: "沿着预定轨迹自动行驶",
                        icon: "triangle.path",
                        isEnabled: $isAutoTracking,
                        onToggle: {
                            sendAutoFunction(type: "TRACK", enabled: $0)
                        }
                    )
                    
                    // 自动避障
                    FunctionToggleRow(
                        title: "自动避障",
                        description: "检测并避开前方障碍物",
                        icon: "exclamationmark.octagon",
                        isEnabled: $isAutoAvoidance,
                        onToggle: {
                            sendAutoFunction(type: "AVOID", enabled: $0)
                        }
                    )
                    
                    // 自动跟随
                    FunctionToggleRow(
                        title: "自动跟随",
                        description: "自动跟随前方目标",
                        icon: "figure.walk.circle",
                        isEnabled: $isAutoFollow,
                        onToggle: {
                            sendAutoFunction(type: "FOLLOW", enabled: $0)
                        }
                    )
                }
                .padding(.horizontal)
                
                Divider()
                    .padding(.vertical)
                
                // 参数设置
                VStack(spacing: 15) {
                    Text("参数设置")
                        .font(.headline)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    // 避障距离
                    SliderSettingRow(
                        title: "避障距离（米）",
                        value: $avoidanceDistance,
                        range: 0.2...1.0,
                        step: 0.1,
                        onChanged: { value in
                            sendParameterSetting(type: "AVOID_DIST", value: value)
                        }
                    )
                    
                    // 跟随速度
                    SliderSettingRow(
                        title: "跟随速度",
                        value: $followSpeed,
                        range: 0.2...1.0,
                        step: 0.1,
                        onChanged: { value in
                            sendParameterSetting(type: "FOLLOW_SPEED", value: value)
                        }
                    )
                }
                .padding(.horizontal)
                
                // 复位所有功能按钮
                Button(action: {
                    resetAllFunctions()
                }) {
                    Text("复位所有功能")
                        .font(.headline)
                        .padding()
                        .frame(maxWidth: .infinity)
                        .background(Color.red)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                }
                .padding(.horizontal)
                .padding(.vertical, 20)
            }
            .padding(.bottom, 30)
        }
    }
    
    // 发送自动功能命令
    private func sendAutoFunction(type: String, enabled: Bool) {
        let command = "AUTO:\(type):\(enabled ? "ON" : "OFF")"
        
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("自动功能命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 发送参数设置命令
    private func sendParameterSetting(type: String, value: Double) {
        let intValue = Int(value * 100)
        let command = "PARAM:\(type):\(intValue)"
        
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("参数设置命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
    
    // 复位所有功能
    private func resetAllFunctions() {
        isAutoTracking = false
        isAutoAvoidance = false
        isAutoFollow = false
        
        let command = "AUTO:RESET:ALL"
        
        if let data = command.data(using: .utf8) {
            tcpCarService.sendData(data) { success in
                print("复位命令发送\(success ? "成功" : "失败"): \(command)")
            }
        }
    }
}

// 功能开关行
struct FunctionToggleRow: View {
    var title: String
    var description: String
    var icon: String
    @Binding var isEnabled: Bool
    var onToggle: (Bool) -> Void
    
    var body: some View {
        HStack {
            // 图标
            Image(systemName: icon)
                .font(.title2)
                .foregroundColor(isEnabled ? .blue : .gray)
                .frame(width: 40, height: 40)
            
            // 文本说明
            VStack(alignment: .leading) {
                Text(title)
                    .font(.headline)
                Text(description)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            Spacer()
            
            // 开关
            Toggle("", isOn: Binding(
                get: { isEnabled },
                set: {
                    isEnabled = $0
                    onToggle($0)
                }
            ))
            .labelsHidden()
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(10)
    }
}

// 滑块设置行
struct SliderSettingRow: View {
    var title: String
    @Binding var value: Double
    var range: ClosedRange<Double>
    var step: Double
    var onChanged: (Double) -> Void
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Text(title)
                    .font(.headline)
                
                Spacer()
                
                Text("\(Int(value * 100))%")
                    .foregroundColor(.secondary)
            }
            
            Slider(
                value: Binding(
                    get: { value },
                    set: {
                        value = $0
                        onChanged($0)
                    }
                ),
                in: range,
                step: step
            )
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(10)
    }
}

// 预览
struct AutoFunctionsView_Previews: PreviewProvider {
    static var previews: some View {
        AutoFunctionsView()
            .environmentObject(TCPCarService())
    }
} 